package com.swingson.properties.impl;

import com.swingson.SwingsonGui;
import com.swingson.Utils;
import com.swingson.exceptions.SwingsonException;
import com.swingson.jsonparser.JsonElement;
import com.swingson.properties.impl.PropertyProcessors.PrimitivePropertyProcessor;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.swing.JComponent;

/**
 * @author sad
 */
public class ColorPropertyProcessor extends PrimitivePropertyProcessor {

    private static final Pattern colorPattern = Pattern.compile("\\#[0-9a-f]{6}");
    private static final Map<String, Color> colorMap = new HashMap<String, Color>();

    static {
        colorMap.put("black", Color.BLACK);
        colorMap.put("blue", Color.BLUE);
        colorMap.put("cyan", Color.CYAN);
        colorMap.put("dark_gray", Color.DARK_GRAY);
        colorMap.put("gray", Color.GRAY);
        colorMap.put("green", Color.GREEN);
        colorMap.put("light_gray", Color.LIGHT_GRAY);
        colorMap.put("magenta", Color.MAGENTA);
        colorMap.put("orange", Color.ORANGE);
        colorMap.put("red", Color.RED);
        colorMap.put("white", Color.WHITE);
        colorMap.put("yellow", Color.YELLOW);
    }

    @Override
    protected Object getValue(JsonElement jsonElement, JComponent component, SwingsonGui gui, String propertyName) {
        String value = jsonElement.getAsString();
        value = value.trim().toLowerCase();
        if (colorPattern.matcher(value).matches()) {
            return parseHexColor(value.substring(1));
        }
        if (value.startsWith("#")) {
            throw new SwingsonException(String.format("Hex color for property '%s' should contain only digits and a-f symbols.", propertyName));
        }
        if (colorMap.containsKey(value)) {
            return colorMap.get(value);
        }
        
        String closestColor=Utils.getClosestString(value,colorMap.keySet());
        throw new SwingsonException("Unrecognized color '"+value+"' in property '"+propertyName+"'. Maybe you meant '"+closestColor+"'?");
    }

    private Color parseHexColor(String hexcolor) {
        return Utils.parseHexColor(hexcolor);
    }
}
